package com.j4dream.property.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.common.collect.ImmutableList;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserDto implements UserDetails {
    private int id;
    private String email;
    private String name;
    private String firstName;
    private String lastName;
    private String password;
    private int loginFailCount;
    private boolean enabled;
    private Long createTime;
    private String title;
    private String signature;
    private String phone;
    private int notifyCount;
    private String group;
    private String country;
    @JsonIgnore
    private String province;
    @JsonIgnore
    private String city;
    private String avatar;
    private String address;
    private List<Integer> tags = new ArrayList<>();

    private List<RoleDto> roles = new ArrayList();

    private Geographic geographic;

    @Override
    public boolean isAccountNonLocked() {
        return loginFailCount <= 5;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    @Override
    public String getUsername() {
        return this.email;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return getRoles().stream().flatMap(roleDto -> roleDto.getPermissions().stream())
                .map(p -> new SimpleGrantedAuthority(p.getName())).collect(Collectors.toList());
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Data
    @NoArgsConstructor
    public static class Geographic {
        private KeyLabel city;
        private KeyLabel province;
    }

}
